<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\helpers\traits\SearchDataForModel;
use think\exception\ValidateException;
use think\Request;

class Recruit extends BaseController
{

    use SearchDataForModel;
    /**
     * @User: 刘海龙
     * @Date: 2021/3/11
     * @Time: 18:11
     * @return \think\response\Json
     * 列表
     */
    public function getRecruitList()
    {
        $limit = $this->request->param('limit', 3);
        $data = $this->search(new \app\api\model\Recruit(), [], $limit);
        return $this->response($data);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/3/11
     * @Time: 18:11
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取唯一信息
     */
    public function showRecruit($id)
    {
        $data = \app\api\model\Recruit::find($id)->toArray();
        if (is_null($data)) {
            return $this->response(404, '不存在');
        }
        return $this->response($data);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/3/11
     * @Time: 18:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *  保存招聘信息
     */
    public function saveRecruit()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                \app\api\validate\Recruit::rules($id),
                \app\api\validate\Recruit::msg());
            if ($validator) {
                $data = $this->request->param();
                $data['create_id'] = $this->request->uid;
                if (intval($id) === 0) {
                    \app\api\model\Recruit::create($data);
                } else {
                    $rec = \app\api\model\Recruit::find($id);
                    $rec->save($data);
                }
                return $this->response();
            }
        } catch (ValidateException $exception) {
            return $this->response(403, $exception->getError());
        }

    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/3/11
     * @Time: 18:13
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除
     */
    public function delRecruit($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $eval = \app\api\model\Recruit::find($id);
            if (is_null($eval)) {
                return $this->response(404, '该信息不存在');
            }
            $eval->delete();
        }
        return $this->response();
    }
}
